<?php

namespace App\Libs\Company\SheetTemplateHandler;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

class Export
{
    public static $horizontalAlignMap = [
        Alignment::HORIZONTAL_GENERAL,
        Alignment::HORIZONTAL_LEFT,
        Alignment::HORIZONTAL_CENTER,
        Alignment::HORIZONTAL_RIGHT,
        Alignment::HORIZONTAL_JUSTIFY,
    ];
    public static $verticalAlignMap = [
        Alignment::VERTICAL_JUSTIFY,
        Alignment::VERTICAL_TOP,
        Alignment::VERTICAL_CENTER,
        Alignment::VERTICAL_BOTTOM,
    ];

    public static function export($univerData, $name = 'sheet')
    {
        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->setActiveSheetIndex(0);

        $xfMap = [];
        foreach ($univerData['styles'] as $key => $value) {
            $style = new \PhpOffice\PhpSpreadsheet\Style\Style;

            $styleArray = [];
            if (isset($value['fs'])) {
                $styleArray['font']['size'] = $value['fs'];
            }
            if (isset($value['bl'])) {
                $styleArray['font']['bold'] = $value['bl'];
            }
            if (isset($value['it'])) {
                $styleArray['font']['italic'] = $value['it'];
            }
            if (isset($value['bg']['rgb'])) {
                if (preg_match('/rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/', $value['bg']['rgb'], $matches)) {
                    $styleArray['fill']['color']['rgb'] = sprintf("%02x%02x%02x", $matches[1], $matches[2], $matches[3]);
                }
            }
            if (isset($value['cl']['rgb'])) {
                if (preg_match('/rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/', $value['cl']['rgb'], $matches)) {
                    $styleArray['font']['color']['rgb'] = sprintf("%02x%02x%02x", $matches[1], $matches[2], $matches[3]);
                }
            }
            if (isset($value['ht'])) {
                $styleArray['alignment']['horizontal'] = self::$horizontalAlignMap[$value['ht']];
            }
            if (isset($value['vt'])) {
                $styleArray['alignment']['vertical'] = self::$horizontalAlignMap[$value['vt']];
            }
            if (isset($value['tb']) && $value['tb'] == 3) {
                $styleArray['alignment']['wrapText'] = true;
            }

            $style->applyFromArray($styleArray);

            $worksheet->getParentOrThrow()->addCellXf($style);
            $xfMap[$key] = $style->getIndex();
        }

        if (isset($univerData['sheets']['sheet-01']['mergeData'])) {
            foreach ($univerData['sheets']['sheet-01']['mergeData'] as $merge) {
                $spreadsheet->getActiveSheet()->mergeCells([
                    $merge['startColumn'] + 1,
                    $merge['startRow'] + 1,
                    $merge['endColumn'] + 1,
                    $merge['endRow'] + 1,
                ]);
            }
        }

        if (isset($univerData['sheets']['sheet-01']['rowData'])) {
            foreach ($univerData['sheets']['sheet-01']['rowData'] as $rowIndex => $row) {
                if (isset($row['h'])) {
                    $worksheet->getRowDimension($rowIndex + 1)->setRowHeight($row['h'], 'px');
                }
            }
        }

        if (isset($univerData['sheets']['sheet-01']['columnData'])) {
            foreach ($univerData['sheets']['sheet-01']['columnData'] as $columnIndex => $column) {
                if (isset($column['w'])) {
                    $worksheet->getColumnDimensionByColumn($columnIndex + 1)->setWidth($column['w'], 'px');
                }
            }
        }

        if (isset($univerData['sheets']['sheet-01']['cellData'])) {
            foreach ($univerData['sheets']['sheet-01']['cellData'] as $rowIndex => $row) {
                foreach ($row as $columnIndex => $cell) {
                    if (!is_numeric($columnIndex)) {
                        continue;
                    }
                    $c = $worksheet->getCell([(int) $columnIndex + 1, (int) $rowIndex + 1]);
                    if (!empty(isset($cell['p']['body']['dataStream']))) {
                        $c->setValue(trim($cell['p']['body']['dataStream'], "\r\n"));
                    } elseif (isset($cell['v'])) {
                        $c->setValue($cell['v']);
                    }
                    if (isset($cell['s'])) {
                        $c->setXfIndex($xfMap[$cell['s']]);
                    }
                    if (isset($cell['f'])) {
                        $c->setValue($cell['f']);
                    }
                }
            }
        }

        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST,GET,OPTIONS');
        header('Access-Control-Expose-Headers: Content-Disposition');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8');

        header('Content-Disposition: attachment;filename="' . urlencode(str_replace("\r", '', $name)) . '.xlsx"');
        header('Cache-Control: max-age=0');

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }
}
